package sushil.luc.gui;


import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import sushil.luc.navigation.GetRouteTask;
import sushil.luc.truckersmartrfid.R;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.Toast;

public class TruckerMapFragment extends Fragment implements LocationListener{

	private View view;
	private GoogleMap map;
	private LocationManager locationManager;
	 private static final long MIN_TIME = 400;
	 private static final float MIN_DISTANCE = 1000;
	 private boolean GPSenabled;
	 private Button btnNavigate;
	 public static String customerAdress;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		//only assign the view if it was not already assigned
		if (view==null)
		{
			view = inflater.inflate(R.layout.truckermap, container, false);
		}
		// get the Map and initialize it
		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
		
		 // Enabling MyLocation in Google Map
		map.setMyLocationEnabled(true);
		map.getUiSettings().setZoomControlsEnabled(true);
		map.getUiSettings().setCompassEnabled(true);
		map.getUiSettings().setMyLocationButtonEnabled(true);
		map.getUiSettings().setAllGesturesEnabled(true);
		map.setTrafficEnabled(true);
		map.animateCamera(CameraUpdateFactory.zoomTo(10));
		
		// init the Button to navigate to the client
		btnNavigate = (Button) view.findViewById(R.id.navigation);
		btnNavigate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// check if there is an address to navigate to
				if (customerAdress!=null)
				{
					// get from the text adress an Latitude and Longtitude location
					Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
					List<Address> addresses; 
					try {
						addresses = geocoder.getFromLocationName(customerAdress, 1);
						Address address = addresses.get(0);
						if(address!=null) {
						    double latitude = address.getLatitude();
						    double longitude = address.getLongitude();
						    // start the navigation
						    navigateTo(new LatLng(latitude, longitude));
						}
						else
						{
							// inform the user if there was a problem
							showMessage("No Navigation available");
						}
					} catch (IOException e) {
						showMessage("Error appeared, No Navigation available");
						e.printStackTrace();
					}
				}
				else
				{
					// the trucker did not finish a ticket
					showMessage("No Navigation available. Please check first an entire Ticket.");
				}

			}
		});
		
		return view;
	}
	
	public void onResume()
	{
		// init LocationManager and check if the GPS Sensor is turned on
		locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    	GPSenabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    	//If the GPS is not activated, tell the user
    	if (!GPSenabled)
    	{
    		// try to get updates from the network
    		 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
    		 showMessage("Please activate the GPS Sensor!");
    	}
    	else
    	{
    		// get updates from the GPS
    		 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
    	}

    	super.onResume();
	}
	
	/**
	 * Displays the route from the truckers current position to the given navigation on the map
	 * @param destination
	 */
	public void navigateTo(LatLng destination)
	{
		// clear everything from the map
		map.clear();
		
		// check if we have a location from the GPS sensor
		Location temp = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (temp == null)
		{
			// no location from the gps, lets try the network
			Log.d("TruckerMapFragment","Take Network position");
			temp = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		}
		else
		{
			Log.d("TruckerMapFragment","Take GPS position");
		}
		
		if (temp!=null)
		{
			// if we have some position
			
			LatLng myPosition = new LatLng(temp.getLatitude(), temp.getLongitude());
			
			Log.d("TruckerMapFragment", myPosition.toString());
			
			// calculate the route
			GetRouteTask getRoute = new GetRouteTask(getActivity(), myPosition, destination, map);
			getRoute.execute();
		}
		else
		{
			showMessage("Can't find your current positon");
		}
	}


	@Override
	public void onLocationChanged(Location location) {
		//if the truckers location changes, center the map to the new position
		   LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
		   CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
		   map.animateCamera(cameraUpdate);
		
	}


	@Override
	public void onProviderDisabled(String provider) {
		// if the GPS provider is disabled tell the trucker to turn it on
		if (provider.equals(LocationManager.GPS_PROVIDER))
		{
      	  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
      	  startActivity(intent);
		}	
	}


	@Override
	public void onProviderEnabled(String provider) {
		// if the GPS sensor is turned on, request updates from it
		if (provider.equals(LocationManager.GPS_PROVIDER))
		{
			 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
		}
	}


	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		
	}
	
	
	/**
     * Show a Toast with the given Text
     * @param text
     */
    private void showMessage(String text)
    {
    	Toast toast= Toast.makeText(getActivity().getApplicationContext(),text, Toast.LENGTH_LONG);
		toast.show();
    }
}
